<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="审核状态" prop="auditStatus">
        <el-select v-model="queryParams.auditStatus" clearable placeholder="请选择" style="width: 140px;">
          <el-option label="待审核" :value="0" />
          <el-option label="已通过" :value="1" />
          <el-option label="已拒绝" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="竞赛" prop="competitionId">
        <el-select v-model="queryParams.competitionId" clearable placeholder="请选择竞赛" style="width: 200px;">
          <el-option 
            v-for="competition in competitionList" 
            :key="competition.id" 
            :label="competition.name" 
            :value="competition.id" 
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['race:competitionResult:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['race:competitionResult:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['race:competitionResult:remove']">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" prop="id" align="center" width="80" />
      <el-table-column label="成果物名称" prop="resultName" align="center" min-width="150" show-overflow-tooltip />
      <el-table-column label="提交用户" prop="userName" align="center" width="120" />
      <el-table-column label="竞赛ID" prop="competitionId" align="center" width="80" />
      <el-table-column label="报名ID" prop="signupId" align="center" width="80" />
      <el-table-column label="文件大小" prop="fileSize" align="center" width="100">
        <template #default="scope">
          {{ formatFileSize(scope.row.fileSize) }}
        </template>
      </el-table-column>
      <el-table-column label="提交时间" prop="submitTime" align="center" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.submitTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" prop="auditStatus" align="center" width="100">
        <template #default="scope">
          <el-tag :type="getAuditStatusType(scope.row.auditStatus)" size="small">
            {{ getAuditStatusText(scope.row.auditStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审核人" prop="auditorName" align="center" width="120" />
      <el-table-column label="审核时间" prop="auditTime" align="center" width="180">
        <template #default="scope">
          <span v-if="scope.row.auditTime">{{ parseTime(scope.row.auditTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleDetail(scope.row)" size="small">详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['race:competitionResult:edit']" size="small">修改</el-button>
          <el-button link type="success" icon="Check" @click="handleAudit(scope.row, 1)" v-hasPermi="['race:competitionResult:audit']" size="small" v-if="scope.row.auditStatus === 0">通过</el-button>
          <el-button link type="danger" icon="Close" @click="handleAudit(scope.row, 2)" v-hasPermi="['race:competitionResult:audit']" size="small" v-if="scope.row.auditStatus === 0">拒绝</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['race:competitionResult:remove']" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改竞赛成果物对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="竞赛" prop="competitionId">
              <el-select v-model="form.competitionId" placeholder="请选择竞赛" style="width: 100%" @change="handleCompetitionChange">
                <el-option 
                  v-for="competition in competitionList" 
                  :key="competition.id" 
                  :label="competition.name" 
                  :value="competition.id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报名信息" prop="signupId">
              <el-select v-model="form.signupId" placeholder="请选择报名信息" style="width: 100%" :disabled="!form.competitionId">
              <el-option 
                v-for="signup in signupList" 
                :key="signup.id" 
                :label="`${signup.participantName || '未知'} - ${signup.contactPhone || '未知'}`" 
                :value="signup.id" 
              />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="成果物名称" prop="resultName">
              <el-input v-model="form.resultName" placeholder="自动从文件名获取" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="提交用户" prop="userName">
              <el-input v-model="form.userName" placeholder="当前登录用户" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="成果物描述" prop="resultDescription">
          <el-input v-model="form.resultDescription" type="textarea" :rows="3" placeholder="请输入成果物描述" />
        </el-form-item>
        
        <el-form-item label="上传文件" prop="file">
          <ZipFileUpload
            ref="zipUploadRef"
            @upload-success="handleZipUploadSuccess"
            @upload-error="handleZipUploadError"
          />
        </el-form-item>
        
        <el-form-item label="文件路径" prop="filePath">
          <el-input v-model="form.filePath" placeholder="自动填入" disabled />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="文件大小" prop="fileSize">
              <el-input v-model="form.fileSize" placeholder="自动填入" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文件MD5" prop="fileMd5">
              <el-input v-model="form.fileMd5" placeholder="自动填入" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="审核状态" prop="auditStatus">
              <el-select v-model="form.auditStatus" placeholder="请选择审核状态" style="width: 100%">
                <el-option label="待审核" :value="0" />
                <el-option label="已通过" :value="1" />
                <el-option label="已拒绝" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审核人" prop="auditorName">
              <el-input v-model="form.auditorName" placeholder="当前登录用户" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="审核分数" prop="auditScore">
          <el-input-number 
            v-model="form.auditScore" 
            :min="0" 
            :max="100" 
            :precision="2" 
            placeholder="请输入审核分数（0-100分）"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog title="成果物审核" v-model="auditOpen" width="500px" append-to-body>
      <el-form ref="auditFormRef" :model="auditForm" :rules="auditRules" label-width="100px">
        <el-form-item label="成果物名称">
          <el-input v-model="auditForm.resultName" disabled />
        </el-form-item>
        <el-form-item label="提交用户">
          <el-input v-model="auditForm.userName" disabled />
        </el-form-item>
        <el-form-item label="审核结果" prop="auditStatus">
          <el-radio-group v-model="auditForm.auditStatus">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核分数" prop="auditScore">
          <el-input-number 
            v-model="auditForm.auditScore" 
            :min="0" 
            :max="100" 
            :precision="2" 
            placeholder="请输入审核分数（0-100分）"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAudit">确 定</el-button>
          <el-button @click="cancelAudit">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 详情对话框 -->
    <el-dialog title="成果物详情" v-model="detailOpen" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="成果物ID">{{ detailForm.id }}</el-descriptions-item>
        <el-descriptions-item label="成果物名称">{{ detailForm.resultName }}</el-descriptions-item>
        <el-descriptions-item label="提交用户">{{ detailForm.userName }}</el-descriptions-item>
        <el-descriptions-item label="竞赛ID">{{ detailForm.competitionId }}</el-descriptions-item>
        <el-descriptions-item label="报名ID">{{ detailForm.signupId }}</el-descriptions-item>
        <el-descriptions-item label="文件大小">{{ formatFileSize(detailForm.fileSize) }}</el-descriptions-item>
        <el-descriptions-item label="文件MD5">{{ detailForm.fileMd5 }}</el-descriptions-item>
        <el-descriptions-item label="提交时间">{{ parseTime(detailForm.submitTime) }}</el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <el-tag :type="getAuditStatusType(detailForm.auditStatus)">
            {{ getAuditStatusText(detailForm.auditStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="审核人">{{ detailForm.auditorName || '未审核' }}</el-descriptions-item>
        <el-descriptions-item label="审核时间">{{ detailForm.auditTime ? parseTime(detailForm.auditTime) : '未审核' }}</el-descriptions-item>
        <el-descriptions-item label="审核分数" :span="2">{{ detailForm.auditScore || '未评分' }}</el-descriptions-item>
        <el-descriptions-item label="成果物描述" :span="2">{{ detailForm.resultDescription || '无' }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detailForm.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, getCurrentInstance } from 'vue'
import { listCompetitionResult, getCompetitionResult, addCompetitionResult, updateCompetitionResult, delCompetitionResult, auditCompetitionResult } from '@/api/race/competitionResult'
import { listCompetition } from '@/api/race/competition'
import { listCompetitionSignup } from '@/api/race/competitionSignup'
import useUserStore from '@/store/modules/user'
import ZipFileUpload from '@/components/ZipFileUpload/index.vue'

const { proxy } = getCurrentInstance()
const userStore = useUserStore()

const list = ref([])
const zipUploadRef = ref()
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)
const open = ref(false)
const auditOpen = ref(false)
const detailOpen = ref(false)
const title = ref('')
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const competitionList = ref([])
const signupList = ref([])
const formFileList = ref([])

const data = reactive({
  form: {},
  auditForm: {},
  detailForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    auditStatus: null,
    competitionId: null
  },
  rules: {
    competitionId: [
      { required: true, message: "竞赛ID不能为空", trigger: "blur" }
    ],
    signupId: [
      { required: true, message: "报名ID不能为空", trigger: "blur" }
    ],
    resultName: [
      { required: true, message: "成果物名称不能为空", trigger: "blur" }
    ],
    userName: [
      { required: true, message: "提交用户名不能为空", trigger: "blur" }
    ]
  },
  auditRules: {
    auditStatus: [
      { required: true, message: "请选择审核结果", trigger: "change" }
    ],
    auditScore: [
      { required: true, message: "审核分数不能为空", trigger: "blur" },
      { type: "number", min: 0, max: 100, message: "审核分数必须在0-100之间", trigger: "blur" }
    ]
  },
})

const { queryParams, form, auditForm, detailForm, rules, auditRules } = toRefs(data)

/** 查询竞赛成果物列表 */
function getList() {
  loading.value = true
  listCompetitionResult(queryParams.value).then(response => {
    list.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 获取竞赛列表（已完赛的竞赛） */
function getCompetitionList() {
  // 获取所有竞赛，然后在前端过滤出已完赛的竞赛
  listCompetition({}).then(response => {
    const allCompetitions = response.rows || []
    // 过滤出已完赛的竞赛（状态为4：已完赛）
    competitionList.value = allCompetitions.filter(competition => 
      competition.competitionStatus === 4
    )
  })
}

/** 竞赛选择变化时获取报名信息 */
function handleCompetitionChange(competitionId) {
  if (competitionId) {
    const query = {
      competitionId: competitionId
    }
    listCompetitionSignup(query).then(response => {
      signupList.value = response.rows || []
      console.log('报名信息数据:', signupList.value)
    })
  } else {
    signupList.value = []
    form.value.signupId = null
  }
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// ZIP文件上传成功处理
function handleZipUploadSuccess(fileData) {
  console.log('ZIP文件上传成功:', fileData)
  
  // 自动设置成果物名称
  const fileName = fileData.fileName.replace(/\.[^/.]+$/, "")
  form.value.resultName = fileName
  
  // 填充文件信息
  form.value.filePath = fileData.filePath
  form.value.fileSize = fileData.fileSize
  form.value.fileMd5 = fileData.fileMd5
  
  console.log('表单文件信息已填充:', {
    resultName: form.value.resultName,
    filePath: form.value.filePath,
    fileSize: form.value.fileSize,
    fileMd5: form.value.fileMd5
  })
  
  // 触发表单验证更新
  proxy.$nextTick(() => {
    proxy.$refs["formRef"].validateField('resultName')
  })
}

// ZIP文件上传失败处理
function handleZipUploadError(error) {
  console.error('ZIP文件上传失败:', error)
  // 清空文件信息
  form.value.filePath = null
  form.value.fileSize = null
  form.value.fileMd5 = null
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    competitionId: null,
    signupId: null,
    userId: userStore.id,
    userName: userStore.nickName || userStore.name,
    resultName: null,
    resultDescription: null,
    filePath: null,
    fileSize: null,
    fileMd5: null,
    submitTime: null,
    auditStatus: 0,
    auditOpinion: null,
    auditorId: userStore.id,
    auditorName: userStore.nickName || userStore.name,
    auditTime: null,
    remark: null
  }
  formFileList.value = []
  signupList.value = []
  
  // 重置ZIP上传组件
  if (zipUploadRef.value) {
    zipUploadRef.value.reset()
  }
  
  proxy.resetForm("formRef")
}

// 审核取消按钮
function cancelAudit() {
  auditOpen.value = false
  resetAudit()
}

// 审核表单重置
function resetAudit() {
  auditForm.value = {
    id: null,
    auditStatus: null,
    auditScore: null
  }
  proxy.resetForm("auditFormRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加竞赛成果物"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const id = row.id || ids.value
  getCompetitionResult(id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改竞赛成果物"
  })
}

/** 详情按钮操作 */
function handleDetail(row) {
  getCompetitionResult(row.id).then(response => {
    detailForm.value = response.data
    detailOpen.value = true
  })
}

/** 审核按钮操作 */
function handleAudit(row, status) {
  resetAudit()
  auditForm.value = {
    id: row.id,
    resultName: row.resultName,
    userName: row.userName,
    auditStatus: status,
    auditScore: null
  }
  auditOpen.value = true
}

// 表单文件上传前验证
function beforeFormUpload(file) {
  const isZip = file.name.toLowerCase().endsWith('.zip')
  const isLt100M = file.size / 1024 / 1024 < 100

  if (!isZip) {
    proxy.$modal.msgError('只能上传ZIP格式的压缩包文件!')
    return false
  }
  if (!isLt100M) {
    proxy.$modal.msgError('文件大小不能超过100MB!')
    return false
  }
  
  return true
}


/** 提交按钮 */
function submitForm() {
  proxy.$refs["formRef"].validate(valid => {
    if (valid) {
      // 检查文件是否已上传
      if (formFileList.value.length > 0 && !form.value.filePath) {
        proxy.$modal.msgError('请等待文件上传完成后再提交')
        return
      }
      
      // 检查必填字段
      if (!form.value.filePath || form.value.filePath === '') {
        proxy.$modal.msgError('请先上传文件')
        return
      }
      
      // 直接保存成果物记录
      saveResult()
    }
  })
}

/** 保存成果物记录 */
function saveResult() {
  if (form.value.id != null) {
    updateCompetitionResult(form.value).then(response => {
      proxy.$modal.msgSuccess("修改成功")
      open.value = false
      getList()
    })
  } else {
    addCompetitionResult(form.value).then(response => {
      proxy.$modal.msgSuccess("新增成功")
      open.value = false
      getList()
    })
  }
}

/** 提交审核 */
function submitAudit() {
  proxy.$refs["auditFormRef"].validate(valid => {
    if (valid) {
      auditCompetitionResult(auditForm.value).then(response => {
        proxy.$modal.msgSuccess("审核成功")
        auditOpen.value = false
        getList()
      })
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除竞赛成果物编号为"' + _ids + '"的数据项？').then(function() {
    return delCompetitionResult(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 格式化文件大小 */
function formatFileSize(size) {
  if (!size) return '0 B'
  const units = ['B', 'KB', 'MB', 'GB']
  let unitIndex = 0
  let fileSize = size
  
  while (fileSize >= 1024 && unitIndex < units.length - 1) {
    fileSize /= 1024
    unitIndex++
  }
  
  return Math.round(fileSize * 100) / 100 + ' ' + units[unitIndex]
}

/** 获取审核状态文本 */
function getAuditStatusText(status) {
  const statusMap = {
    0: '待审核',
    1: '已通过',
    2: '已拒绝'
  }
  return statusMap[status] || '未知'
}

/** 获取审核状态类型 */
function getAuditStatusType(status) {
  const typeMap = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return typeMap[status] || 'info'
}

getList()
getCompetitionList()
</script>
